package data

import (
    "database/sql"
    "encoding/json"
    _ "github.com/go-sql-driver/mysql"
)

// ExecSql 执行 sql 语句操作数据库, 可以是 增、删、改 语句
func ExecSql(sqlStr string) bool {
    db, err := Db()
    defer db.Close()
    if err != nil {
        return false
    }
    row, err2 := db.Exec(sqlStr)
    if err2 != nil {
        return false
    }
    num, _ := row.RowsAffected()
    if num > 0 {
        return true
    }
    return false
}

// GetRow 查询单条数据
func GetRow(sqlStr string) (row *sql.Row) {
    db, err := Db()
    defer db.Close()
    if err != nil {
        return nil
    }
    row = db.QueryRow(sqlStr)
    return row
}

// GetRows 查询数据集合
func GetRows(sqlStr string) (rows *sql.Rows) {
    db, err := Db()
    defer db.Close()
    if err != nil {
        return nil
    }
    stmt, err2 := db.Prepare(sqlStr)
    defer stmt.Close()
    if err2 != nil {
        return nil
    }
    rows, err = stmt.Query()
    //rows, err = db.Query(sql)
    if err != nil {
        return nil
    }
    return rows
}

// Rows2Array 数据集转数组
func Rows2Array(rows *sql.Rows) (data []map[string]interface{}, err error) {
    columns, e := rows.Columns()
    if e != nil {
        return nil, e
    }
    c := len(columns)
    values := make([]interface{}, c)
    vTrs := make([]interface{}, c)
    for rows.Next() {
        for i := 0; i < c; i++ {
            vTrs[i] = &values[i]
        }
        er := rows.Scan(vTrs...)
        if er != nil {
            return nil, er
        }
        entry := make(map[string]interface{})
        for i, col := range columns {
            var v interface{}
            val := values[i]
            b, ok := val.([]byte)
            if ok {
                v = string(b)
            } else {
                v = val
            }
            entry[col] = v
        }
        data = append(data, entry)
    }
    return data, err
}

// Array2Json 数组转 json
func Array2Json(data any) (jsonStr string) {
    bs, err := json.Marshal(data)
    if err != nil {
        return ""
    }
    jsonStr = string(bs)
    return jsonStr
}
